package com.hzdh.account.controller.login;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSONObject;
import com.hzdh.account.commom.Message;
import com.hzdh.account.commom.validate.AjaxResponse;
import com.hzdh.account.entity.login.User;
import com.hzdh.account.request.login.UserRequest;
import com.hzdh.account.service.UserService;
import com.hzdh.account.utils.HttpClientUtils;

@Controller
@RequestMapping("/")
public class LoginController {

	@Autowired
	private UserService userService;

	@RequestMapping("/login")
	private String loginView() {
		return "login";
	}

	@ResponseBody
	@RequestMapping("/author")
	public Object loginAuthor(UserRequest user) {
		JSONObject jsonObject = new JSONObject();
		try {
			User us = userService.selectUserByConsition(user);
			// 将user信息放在session中
			HttpSession session = getRequest().getSession();
			session.setAttribute("userSession", us);
			jsonObject.put("user", us);
			jsonObject.put("success", "查询成功!");
		} catch (Exception e) {
			jsonObject.put("fail", "查询失败!");
		}
		return jsonObject;
	}

	@RequestMapping("/login/out")
	public String loginOut(HttpServletRequest request) {
		
		HttpSession session = request.getSession();
		if (session != null) {
			User user = (User)session.getAttribute("userSession");
			session.invalidate();
		}
		return "forward:/login";
	}
	
	@ResponseBody
	@RequestMapping(value = "/login/image")
	public String getBgImage() {
		String url = "https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=zh-CN";
		JSONObject jsonObject = new JSONObject();
		String res = null;
		try {
			res = HttpClientUtils.requestByGetMethod(url);
			if(res != null) {
					res = res.substring(res.indexOf("{"), res.indexOf("}") + 1) + "]}";
					jsonObject = JSONObject.parseObject(res);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return res;
	}
	
	private HttpServletRequest getRequest() {
		return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
	}
}
